//
//  IPhoneViewController.m
//  baodongPro
//
//  Created by feng on 16/2/26.
//  Copyright © 2016年 proper. All rights reserved.
//mpo


#define personPhoto     @"personPhoto"
#define user_defult  [NSUserDefaults standardUserDefaults]
#import "MineViewController.h"
#import "MyClockViewController.h"
#import <ContactsUI/ContactsUI.h>
#import "UIView+FBDQuickCreateUI.h"
#import "BaseViewController.h"
#import "HFStretchableTableHeaderView.h"
#import "MineTableViewCell.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "NavBarTools.h"
#import "Tools/ShowAlertTool.h"
@interface MineViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,CNContactPickerDelegate,UITableViewDataSource,UITableViewDelegate>
{
    CGRect topCGRect;
    UIImageView*_topImageBGView;
    
    UITableView*_myTableView;
    NSMutableArray* _myDataList;
    NSMutableArray* _myAllControllerArray;
    NSDictionary* _titleDictionaryAboutVC;
    NSMutableArray* listValueArray;
    UIImageView*personPhotoView;
    HFStretchableTableHeaderView*_stretchableTableHeaderView;
}

@end

@implementation MineViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NavBarTools  defaultTools] settingNavBarColorWithCurrentController:self];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appCurrentUserLoginOut:) name:APP_LOGINOUT_NOTIFACTION object:nil];
    
    [self testUIMotionEffectDemo];
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.view.backgroundColor=[UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    UIBarButtonItem* rightTestItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightBarButtonItemPressed:)];
    
    self.navigationItem.rightBarButtonItem=rightTestItem;
//    UILabel* tipLabel=[self.view fbd_quickCreateUILabelWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 40)];
//    tipLabel.text=@"iOS 9 新框架 获取通讯录";
//    tipLabel.textAlignment=NSTextAlignmentCenter;
//    [self.view addSubview:tipLabel];
//    UIButton* pickerButton=[self.view fbd_quickCreateUIButtonWithFrame:CGRectMake(100, 100, 200, 40)];
//    [pickerButton addTarget:self action:@selector(addPickerbuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:pickerButton];
    
    topCGRect=    CGRectMake(0, 0, ScreenW, 200);
    _topImageBGView=[self.view fbd_quickCreateUIImageViewWithFrame:topCGRect withImageName:nil];
    _topImageBGView.image=[UIImage imageNamed:@"IMG_0324.JPG"];
    _topImageBGView.userInteractionEnabled=YES;
    _topImageBGView.contentMode=UIViewContentModeScaleAspectFit;
    
    
    personPhotoView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [self personImageViewChangeDataToImage];
    personPhotoView.userInteractionEnabled=YES;
    personPhotoView.layer.cornerRadius=CGRectGetHeight(personPhotoView.frame)/2.0;
    personPhotoView.layer.borderWidth=2;
    personPhotoView.layer.borderColor=UIColorFromRGB(0x3990e0).CGColor;
    personPhotoView.backgroundColor=[self.view randomColor];
    [personPhotoView setView_centerX:ScreenW/2.0 centerY:CGRectGetMidY(topCGRect)];
    personPhotoView.clipsToBounds=YES;
    _topImageBGView.backgroundColor=RGBA(115, 248, 202, 1);
    [_topImageBGView addSubview:personPhotoView];
    
    UITapGestureRecognizer* tapForSelectImage=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapForSelectImagePressed:)];
    tapForSelectImage.numberOfTapsRequired=1;
    tapForSelectImage.numberOfTouchesRequired=1;
    [personPhotoView addGestureRecognizer:tapForSelectImage];
    
    
    // 数据的初始化
    _myDataList=[NSMutableArray array];
    NSArray* topArray=@[@"姓名",@"生日",@"性别",@"母亲",@"父亲"];
    [_myDataList addObject:topArray];
    
    NSArray*middleArray=@[@"习惯",@"特征",@"日记"];
    [_myDataList addObject:middleArray];
    
    NSArray* footArray=@[@"早教",@"天气预报",@"秒表",@"联系我们",@"设置"];
    [_myDataList addObject:footArray];

    _myAllControllerArray=[NSMutableArray array];
    NSArray* listController=@[@"MineNameViewController",
                              @"MineBirthdayViewController",
                              @"sex",
                              @"MineFatherViewController",
                              @"MineMotherViewController",
                              @"MineHabitViewController",
                              @"MineFeatureViewController",
                              @"MineDiaryViewController",
                              @"MineEarlyTeachViewController",
                              @"MineWeatherReportViewController",
                              @"MyClockViewController",
                              @"ContactUSViewController",
                              @"MineSettingViewController"];
    
    
    

    
    NSMutableArray* listNameController=[NSMutableArray arrayWithArray:topArray];
    [listNameController addObjectsFromArray:middleArray];
    [listNameController addObjectsFromArray:footArray];
    
    
   NSArray*  tmp_listValueArray=@[@"还没有登录呢",@"2015-0X-0X",@"小乖女",@"王MM",@"冯GG",@"早睡早起",@"小胖胖",@"去看看",@"Mum ,Dad, Teach Me Language!",@"今天的天气如何",@"去玩玩",@"欢迎加入我们",@"还有很多好玩的哦！"];
    listValueArray=[NSMutableArray arrayWithArray:tmp_listValueArray];
    if ([USER_D objectForKey:CurrentUserName])
    {
        [listValueArray replaceObjectAtIndex:0 withObject:[USER_D objectForKey:CurrentUserName]];
        
    }
    
    _titleDictionaryAboutVC=[NSDictionary dictionaryWithObjects:listNameController forKeys:listController];
    
    [_myAllControllerArray addObjectsFromArray:listController];
    
    
    
    
    
// 初始化 tableView 视图
    CGFloat originTX=CGRectGetMaxY(self.navigationController.navigationBar.frame);
    _myTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, originTX, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-originTX-49) style:UITableViewStyleGrouped];
    _myTableView.rowHeight=60;
    _myTableView.delegate=self;
    _myTableView.dataSource=self;
    _myTableView.keyboardDismissMode=UIScrollViewKeyboardDismissModeInteractive;
    [self.view addSubview:_myTableView];

    _myTableView.tableHeaderView=_topImageBGView;
    
    

    _stretchableTableHeaderView=[HFStretchableTableHeaderView new];
    
    [_stretchableTableHeaderView stretchHeaderForTableView:_myTableView withView:_topImageBGView];

    
    
    
    
    
    
}

#pragma mark ----- private
-(void) addPickerbuttonClicked:(UIButton*)sender
{

    
    CNContactPickerViewController* numberPickerVC=[[CNContactPickerViewController alloc] init];
    numberPickerVC.delegate=self;
    
    [self presentViewController:numberPickerVC animated:YES completion:^{
        
        NSLog(@"进入了 numberPickerVC 页面");
        
    }];
    
}

-(void)tapForSelectImagePressed:(UITapGestureRecognizer*)tap
{
    [self userAuthoriDevecie];

    }

-(void)userAuthoriDevecie
{

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // Pre iOS 8 -- No camera auth required.
        
    }else {
        // iOS 8 后，全部都要授权
        
        // Thanks: http://stackoverflow.com/a/24684021/2611971
        
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (status) {
            case AVAuthorizationStatusNotDetermined:{
                // 许可对话没有出现，发起授权许可
                
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (granted) {
                            //第一次用户接受
//                            allowBlock();
                            UIImagePickerController* imagePickerVC=[[UIImagePickerController alloc] init];
                            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary ])
                            {
                                
                                
                                return;
                            }
                            imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
                            imagePickerVC.delegate=self;
                            [self presentViewController:imagePickerVC animated:YES completion:nil];
                            

                            
                        }else{
                            //用户拒绝
//                            showAlert(@"已拒绝授权，打开相机失败");
                        }
                    });
                }];
                break;
            }
            case AVAuthorizationStatusAuthorized:{
                // 已经开启授权，可继续
                
                UIImagePickerController* imagePickerVC=[[UIImagePickerController alloc] init];
             
                imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerVC.delegate=self;
                [self presentViewController:imagePickerVC animated:YES completion:nil];
                


                
                break;
            }
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
                // 用户明确地拒绝授权，或者相机设备无法访问
                
                break;
            default:
                break;
        }
}
}


#pragma mark -----  CNContactPickerDelegate

/*!
 * @abstract Invoked when the picker is closed.
 * @discussion The picker will be dismissed automatically after a contact or property is picked.
 */
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker
{

    NSLog(@"contactPickerDidCancel");


}

/*!
 * @abstract Singular delegate methods.
 * @discussion These delegate methods will be invoked when the user selects a single contact or property.
 */
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
{
    NSLog(@"didSelectContact :%@",contact);
    
    
    
    
    

}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
{

    NSLog(@"didSelectContactProperty :%@",contactProperty);

}

/*!
 * @abstract Plural delegate methods.
 * @discussion These delegate methods will be invoked when the user is done selecting multiple contacts or properties.
 * Implementing one of these methods will configure the picker for multi-selection.
 */
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact*> *)contacts
{
    if (_myDataList.count>0)
    {
    [_myDataList  removeAllObjects];
    }
    NSLog(@"didSelectContacts :%@",contacts);

    [contacts enumerateObjectsUsingBlock:^(CNContact * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop){
        
        NSString* everyNameAndNumber=nil;
        if (obj.phoneNumbers.count>0)
        {
           CNLabeledValue* fisrtLabelValue=[obj.phoneNumbers firstObject];
//            fisrtLabelValue labeledValueBySettingLabel:<#(nullable NSString *)#>
            NSLog(@">>>>%@>>>>> %@>>>>>%@>>>>>",fisrtLabelValue.label,
                  fisrtLabelValue.identifier,
                  fisrtLabelValue.value);
            
            CNPhoneNumber* valueDic=fisrtLabelValue.value;
           NSString* allValue= [NSString stringWithFormat:@"%@ : %@",obj.familyName,[valueDic stringValue]];
            NSLog(@"allValue: %@",allValue);
            everyNameAndNumber=allValue;
            
        }
        
        
        [_myDataList addObject:everyNameAndNumber];
        
    }];
    
    [_myTableView reloadData];
    
    
}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperties:(NSArray<CNContactProperty*> *)contactProperties
{


    NSLog(@"didSelectContactProperties :%@",contactProperties);


}

//用户退出登录的时候  我的页面的处理
-(void)appCurrentUserLoginOut:(NSNotification*)sender
{
    [_myTableView setContentOffset:CGPointMake(0, 0)];
//    [_myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    
    
    
    
}



-(void)mineSubViewControllerWillToBePushIntoWithIndex:(NSInteger)index
{

    NSString* indexViewControllerName=    [_myAllControllerArray objectAtIndex:index];
//    BOOL isContain=  [_myAllControllerArray containsObject:indexViewControllerName];
    
    if (indexViewControllerName)
    {

        BaseViewController* indexBaseVC= [[NSClassFromString(indexViewControllerName)  alloc] init];


        if (indexBaseVC)
        {
            indexBaseVC.hidesBottomBarWhenPushed=YES;
            indexBaseVC.title=[_titleDictionaryAboutVC objectForKey:indexViewControllerName];
            indexBaseVC.automaticallyAdjustsScrollViewInsets=NO;
            
            [self.navigationController pushViewController:indexBaseVC animated:YES];

        }else
        {
            NSAssert(indexBaseVC, @"请初始化一个有用的视图控制器");
        
        }
        
    }







}





#pragma mark ---- UITableViewDataSource && UITAbleViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _myDataList.count;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return     [[_myDataList objectAtIndex:section] count];
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* indentifier=@"numbersCells";
    MineTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        cell=[[MineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier withFrame:CGRectMake(0, 0, ScreenW, 60)];
    
    }
    
    cell.textLabel.textColor=[self.view randomColor];
    cell.textLabel.text=[[_myDataList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    NSInteger index_Row =   [self baseGroupTableViewSectionReturnIndexWithIndexPath:indexPath];
    cell.rightValueLable.text=    [listValueArray objectAtIndex:index_Row];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger indexVC_Row=    [self baseGroupTableViewSectionReturnIndexWithIndexPath:indexPath];
//    NSLog(@"测试得到的数据索引：%ld",indexVC_Row);
    [self mineSubViewControllerWillToBePushIntoWithIndex:indexVC_Row];
    
//    UITableViewCell*indexCell=[tableView cellForRowAtIndexPath:indexPath];
    
    
    
    

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    CGFloat yOffset = scrollView.contentOffset.y;
    //向上偏移量变正  向下偏移量变负
    if (yOffset < 0&&fabs(yOffset)<60) {
        CGFloat factor = ABS(yOffset);
        CGRect f = CGRectMake(-(ScreenW*factor/100-ScreenW)/2,-ABS(yOffset)+64, factor+100,100+factor);
        personPhotoView.layer.cornerRadius=(factor+100)/2.0;
        personPhotoView.frame = f;
    
        
    }else {
        CGRect f = _topImageBGView.frame;
        f.origin.y = 0;
        _topImageBGView.frame = f;
    }

    [_stretchableTableHeaderView scrollViewDidScroll:scrollView];


}




- (void)viewDidLayoutSubviews
{
    [_stretchableTableHeaderView resizeView];
}
-(NSInteger)baseGroupTableViewSectionReturnIndexWithIndexPath:(NSIndexPath*)indexPath
{
    NSInteger row=indexPath.row;
    NSInteger section=indexPath.section;
    NSInteger indexForTableView=0;
    for (int i=0;i<_myDataList.count; i++)
    {
        if (i==section)
        {
            break;
        }
        NSInteger _row=[[_myDataList objectAtIndex:i] count];
        indexForTableView+=_row;
        
    }
    indexForTableView+=row;

    return indexForTableView;


}
#pragma mark ------- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    
    personPhotoView.image=image;//[UIImage imageNamed:@"IMG_0299.JPG"];
    NSData* imageData=UIImageJPEGRepresentation(image, 1.0);
    [user_defult  setValue:imageData forKey:personPhoto];
    [user_defult  synchronize];
    [self dismissViewControllerAnimated:YES completion:nil];


}

-(void)personImageViewChangeDataToImage
{
    NSData* photoData=    [user_defult  objectForKey:personPhoto];
    
    personPhotoView.image=[UIImage imageWithData:photoData scale:0.8];


}


#pragma mark ------
-(void)rightBarButtonItemPressed:(id)sender
{

    
    [ShowAlertTool showConfigeWithTitle:@"Mine Title" Message:@"这个功能还没有开发完毕，尽情期待！" ButtonTitleArray:@[@"确定",@"取消"]];
    
    [[ShowAlertTool defaultTool]  showInVC:self sureBlcok:^(UIAlertAction *oneAction) {
        NSLog(@"确定按钮");
    
        
    

    } failedBlock:^(UIAlertAction *oneAction) {
    
            NSLog(@"取消按钮");
    

    }];
}


#pragma  mark ----- UIMotionEffect

-(void)testUIMotionEffectDemo
{

//    UIInterpolatingMotionEffect * xEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
//    xEffect.minimumRelativeValue =  [NSNumber numberWithFloat:-40.0];
//    xEffect.maximumRelativeValue = [NSNumber numberWithFloat:40.0];
//    [self.view  addMotionEffect:xEffect];


    
    UIInterpolatingMotionEffect * yEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
    yEffect.minimumRelativeValue=[NSNumber numberWithFloat:-60];
    yEffect.maximumRelativeValue=[NSNumber numberWithFloat:60];
    [self.view addMotionEffect:yEffect];
    
}



- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    return YES;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
